define(["../common"], function() {
	require.config({
		paths: {
			echarts: './echarts-2.2.1'
	    }
	});
	
	var cancelDoPath = g_shopDomain + "/storePromote/addOrEditDo/json";
	var delDoPath = g_shopDomain + "/storePromote/delDo/json";
	var statusPath = g_shopDomain + "/storePromote/statusDo/json";
	var spCount = $("#spCount").val();

	// 图表选项
	var option = {
	    series : [
	        {
	        	type:'gauge',
	            startAngle: 90,
	            endAngle : -270,
	            precision: 0,               	// 小数精度，默认为0，无小数点
	            splitNumber: 12,             	// 分割段数，默认为5
	            axisLine: {            			// 坐标轴线
	                show: true,        			// 默认显示，属性show控制显示与否
	                lineStyle: {       			// 属性lineStyle控制线条样式
	                    color: [[0.4, '#D2D2D2'],[1, '#13AFE8']], 
	                    width: 1
	                }
	            },
	            axisTick: {            // 坐标轴小标记
	                splitNumber: 5,    // 每份split细分多少段
	                length :3,         // 属性length控制线长
	                lineStyle: {       // 属性lineStyle控制线条样式
	                    color: 'auto'
	                }
	            },
	            axisLabel: {           // 坐标轴文本标签，详见axis.axisLabel
	                formatter: function(v){
	                    switch (v+''){
		                    default: return '';
	                    }
	                }
	            },
	            splitLine: {           // 分隔线
	                length :8,         // 属性length控制线长
	                lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
	                	width: 1,
	                    color: 'auto'
	                }
	            },
	            pointer : {
	            	length : '100%',
	                width : 3,
	                color : '#13AFE8'
	            },
	            detail : {
	                show: false
	            },
	            data:[{value: 0}]
	        }
	    ]
	};
	
	// echart实例集合
	var gauges = [];
	var detailTmp = $("#detailTmp").html();
	
	
	require(['echarts','echarts/chart/gauge'], function (ec) {
    	initCharts(ec);
    	
    	setInterval(function() {
    		initCharts(ec);
    	}, 6e4);
    	
    });
	
	initDetails();
	
	// 类型选中
	(function() {
		var spType = $("#spType").val();
		$("#typeFilter_" + spType).addClass("selected");
	})();


	// 显示详情
	$(".chartItem").hover(function() {
		$(this).children(".popover").show();
	}, function() {
		$(this).children(".popover").hide();
	});

	$(document).on('click', "[id^='statusBt_']", function() {
	
		if (!$(document).showMsg("状态更新中...", 'load', true)) return;
		
		var vars = $(this).attr("id").split("_");
		var promoteId = vars[1];
		var status = vars[2];// enums name
		
		$.post(statusPath, {promoteId: promoteId, status: status}, function(data) {
			if (data.status === 0) {
				
				$(document).showMsg("更新成功！", 'pass');
				
				var $jsonData = $("#jsonData_" + promoteId);
				var sp = $.parseJSON($jsonData.html());// storePromote
				
				sp.status = data.result; // enums ordinal 
				
				// (由于后台逻辑原因进行特殊处理)直接根据时间判定活动状态
				if (sp.status === 0 && sp.startTime < new Date().getTime() && sp.endTime > new Date().getTime()) {
					sp.status = 1;
				}
				
				resetChart(sp);
				resetDetail(sp);
				
				$jsonData.html(JSON.stringify(sp));
				
			} else {
				$this.showMsg(data.message, 'error');
			}
		});
	});

	// 事件：删除促销信息
	$(document).on('click', "[id^='delBt_']", function() {
		var promoteId = ($(this).attr("id").split("_"))[1];
		var $item = $("#item_" + promoteId);
		if ($item.doing()) return;
		
		var msgConfig = {
			id: 'del_' + promoteId,
			type: 'confirm',
			content: "确定要删除促销吗？",
			title: "提示",
			onClose: function() {
				if (this.val()) {
					delDo_();
				}
			}
		};
		
		loadjs(["msgbox"], function() {
			$.msgbox(msgConfig);
		});
		
		function delDo_() {
			$item.showMsg("删除中...", 'load', true);
			$item.fadeTo(null,0.1);
			$.post(delDoPath, {promoteId: promoteId}, function(data) {
				if (data.status === 0) {
					$item.fadeOut(function() {
						$(this).showMsg();
						$(this).remove();
						spCount++;
						if (spCount > 0) {
							$("#addSPItem").show();
						}
					});
				} else {
					$item.showMsg(data.message, 'error');
					$item.fadeTo('fast',1);
				}
			});
		}
	});
	

	function initCharts(ec) {
		
    	$("[id^='chart_']").each(function(i, el) {
    		var id = $(el).attr("id").replace(/chart_/,"");
    		var sp = $.parseJSON($("#jsonData_" + id).html());// goodsPromote
    		
    		resetChart(sp, ec);
    		
    	});
    	
	}
	
	/**
	 * @param ec echart
	 * @param sp storePromote
	 * @param $el
	 */
	function resetChart(sp, ec) {
		
		var myOption = option;
		
		var maxValue = sp.endTime - sp.startTime;
		var value = new Date().getTime() - sp.startTime;
		var wait = 0;
		
		if (sp.startTime > sp.updateTime) {
			maxValue = sp.endTime - sp.updateTime;
			value = new Date().getTime() - sp.updateTime;
			wait = (sp.startTime - sp.updateTime) / (sp.endTime - sp.updateTime);
		}
		
		value = (value / maxValue * 100).toFixed(0);
		
		// 已经完成或者已经取消
		if (value >= 100 || sp.status === 3) {
			value = 100;
			wait = 1;
		}
		
		myOption.series[0].axisLine.lineStyle.color[0][0] = wait;
		myOption.series[0].data[0].value= value;
		
		if (!gauges[sp.promoteId]) {
			gauges[sp.promoteId] = ec.init($("#chart_" + sp.promoteId).get(0));
		}
		gauges[sp.promoteId].setOption(myOption);
	}
	
	function initDetails() {
		
		$("[id^='jsonData_']").each(function(i, el) {
    		var sp = $.parseJSON($(el).html());// goodsPromote
    		resetDetail(sp);
    	});
		
	};
	
	/**
	 * @param sp storePromote
	 */
	function resetDetail(sp) {
		
		var id = sp.promoteId;
		
		var startDate = new Date();
		startDate.setTime(sp.startTime);
		
		var endDate = new Date();
		endDate.setTime(sp.endTime);
		
		var addDate = new Date();
		addDate.setTime(sp.updateTime);
		
		var statusText = "未知";
		if (sp.status === 0) {
			statusText = "未开始";
		} else if (sp.status === 1) {
			statusText = "进行中";
		} else if (sp.status === 2) {
			statusText = "已经结束";
		} else if (sp.status === 3) {
			statusText = "已取消";
		}
		
		var ctrlHtml = '<a id="delBt_' + id + '">删除</a>';
		if (sp.status === 0 || sp.status === 1) {
			ctrlHtml = '<a id="statusBt_' + id + '_CANCELLED">取消</a> | ' + ctrlHtml;
		} else if(sp.status === 3) {
			ctrlHtml = '<a id="statusBt_' + id + '_NOSTART">恢复</a> | ' + ctrlHtml;
		}
		
		var tmp = detailTmp
		.replace(/\-\{id\}\-/g, id)
		.replace(/\-\{timeLength\}\-/g, startDate.distance(endDate))
		.replace(/\-\{startTime\}\-/g, startDate.format("MM-dd hh:mm"))
		.replace(/\-\{endTime\}\-/g, endDate.format("MM-dd hh:mm"))
		.replace(/\-\{addTime\}\-/g, addDate.format("MM-dd hh:mm"))
		.replace(/\-\{statusText\}\-/g, statusText)
		.replace(/\-\{ctrlHtml\}\-/g, ctrlHtml);
		
		var $item = $("#item_" + id);
		$item.find(".popover-content").html(tmp);
		$item.find(".popover").css("margin-left", "-" + $item.find(".popover").outerWidth() + "px");
	}
});
